package dataStructure;

/**
 * @Author xuxin
 * @Date 2021/8/4 23:53
 **/
public class StackUtil<T extends Object> {
    private Object[] elements;

    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    /**
     * 当前数组的容量
     */
    private int space;
    private int tail;

    public StackUtil() {
        this.space = 8;
        this.tail = -1;
        elements = new Object[space];
    }

    public StackUtil(int length) {
        this.space = length;
        this.tail = -1;
        elements = new Object[space];
    }

    /**
     * 入栈
     *
     * @param t
     */
    public void push(T t) {
        //看看是否需要扩容
        if (this.tail + 2 > (this.space * DEFAULT_LOAD_FACTOR)) {
            this.space = this.space * 2;
            Object[] temp = new Object[this.space];
            for (int i = 0; i <= tail; i++) {
                temp[i] = elements[i];
            }
            elements = temp;
        }
        elements[++tail] = t;
    }

    public Object pop() {
        if (this.tail == -1) {
            throw new RuntimeException("栈是空的了");
        }
        return elements[tail--];
    }

    /**
     * @return 栈的长度
     */
    public int size() {
        return tail + 1;
    }

    /**
     * 从栈的最后一个打印到第一个
     */
    public void show() {
        if (this.tail == -1) {
            System.out.println("空栈");
        }
        for (int i = this.tail; i >= 0; i--) {
            System.out.println(elements[i]);
        }
    }

    public int getSpace() {
        return this.space;
    }
}
